#!/usr/bin/env python3
"""
密码重置工具
用于重置用户密码，支持双重哈希验证
"""
import sys
import os
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from sqlalchemy.orm import Session
from core.database import engine, SessionLocal
from models.database import User
from core.auth import get_password_hash

def reset_admin_password(new_password: str = "Admin@123"):
    """重置admin用户密码"""
    
    # 验证密码强度
    if not is_password_strong(new_password):
        print("❌ 密码强度不足！")
        print("密码要求：")
        print("- 最少8位")
        print("- 包含大写字母")
        print("- 包含小写字母") 
        print("- 包含数字")
        print("- 包含特殊字符")
        return False
    
    try:
        # 创建数据库会话
        db = SessionLocal()
        
        # 查找admin用户
        admin_user = db.query(User).filter(User.username == "admin").first()
        
        if not admin_user:
            print("❌ 未找到admin用户，正在创建...")
            
            # 创建admin用户
            admin_user = User(
                username="admin",
                password_hash=get_password_hash(new_password),
                email="admin@example.com",
                role="admin",
                is_active=True
            )
            db.add(admin_user)
            db.commit()
            db.refresh(admin_user)
            
            print(f"✅ Admin用户创建成功！")
            print(f"   用户名: admin")
            print(f"   邮箱: admin@example.com")
            print(f"   新密码: {new_password}")
            
        else:
            # 重置密码
            admin_user.password_hash = get_password_hash(new_password)
            admin_user.updated_at = datetime.now()
            db.commit()
            
            print(f"✅ Admin密码重置成功！")
            print(f"   用户名: admin")
            print(f"   新密码: {new_password}")
            
        return True
        
    except Exception as e:
        print(f"❌ 重置密码时发生错误: {e}")
        return False
    finally:
        db.close()

def is_password_strong(password: str) -> bool:
    """检查密码强度"""
    if len(password) < 8:
        return False
    
    has_upper = any(c.isupper() for c in password)
    has_lower = any(c.islower() for c in password)
    has_digit = any(c.isdigit() for c in password)
    has_special = any(not c.isalnum() for c in password)
    
    return has_upper and has_lower and has_digit and has_special

def list_all_users():
    """列出所有用户"""
    try:
        db = SessionLocal()
        users = db.query(User).all()
        
        print("📋 当前用户列表:")
        print("-" * 50)
        for user in users:
            status = "✅ 活跃" if user.is_active else "❌ 禁用"
            print(f"ID: {user.id} | 用户名: {user.username} | 角色: {user.role} | 状态: {status}")
            
    except Exception as e:
        print(f"❌ 查询用户时发生错误: {e}")
    finally:
        db.close()

def reset_user_password(username: str, new_password: str):
    """重置指定用户密码"""
    if not is_password_strong(new_password):
        print("❌ 密码强度不足！")
        return False
    
    try:
        db = SessionLocal()
        user = db.query(User).filter(User.username == username).first()
        
        if not user:
            print(f"❌ 未找到用户: {username}")
            return False
        
        user.password_hash = get_password_hash(new_password)
        user.updated_at = datetime.now()
        db.commit()
        
        print(f"✅ 用户 {username} 密码重置成功！")
        print(f"   新密码: {new_password}")
        return True
        
    except Exception as e:
        print(f"❌ 重置密码时发生错误: {e}")
        return False
    finally:
        db.close()

def main():
    """主函数"""
    print("🔐 密码重置工具")
    print("=" * 50)
    
    if len(sys.argv) < 2:
        print("用法:")
        print("  python reset_password.py                    # 重置admin密码为 Admin@123")
        print("  python reset_password.py <新密码>            # 重置admin密码为指定密码")
        print("  python reset_password.py <用户名> <新密码>   # 重置指定用户密码")
        print("  python reset_password.py --list             # 列出所有用户")
        print("")
        print("示例:")
        print("  python reset_password.py                    # admin密码重置为 Admin@123")
        print("  python reset_password.py MyP@ssw0rd123      # admin密码重置为 MyP@ssw0rd123")
        print("  python reset_password.py testuser Test@123   # testuser密码重置为 Test@123")
        print("  python reset_password.py --list             # 查看所有用户")
        return
    
    # 列出用户
    if sys.argv[1] == "--list":
        list_all_users()
        return
    
    # 重置admin密码
    if len(sys.argv) == 2:
        new_password = sys.argv[1]
        success = reset_admin_password(new_password)
    # 重置指定用户密码
    elif len(sys.argv) == 3:
        username = sys.argv[1]
        new_password = sys.argv[2]
        if username == "admin":
            success = reset_admin_password(new_password)
        else:
            success = reset_user_password(username, new_password)
    else:
        print("❌ 参数错误！")
        return
    
    if success:
        print("\n🎯 密码重置完成！")
        print("💡 现在可以使用新密码登录系统了")
    else:
        print("\n❌ 密码重置失败！")

if __name__ == "__main__":
    # 导入datetime
    from datetime import datetime
    main()